from __future__ import unicode_literals
from flask import Flask
import ipdb
from flask import request
from flask import jsonify

app = Flask(__name__)
app.config['JSON_AS_ASCII'] = False


def test_free(ip):
    db = ipdb.City("./ipipfree.ipdb")
    strlist1 = db.fields()
    strlist2 = db.find(str(ip), db.languages()[0])
    return dict(zip(strlist1, strlist2))


@app.route('/')
def hello_world():
    return 'access [心.top] for more message.\r\n access [./js] or [./json] to get different user data.'


@app.route("/json", methods=["GET"])
def ip():
    ip = request.environ.get('HTTP_X_REAL_IP', request.remote_addr)
    dict1 = test_free(ip)
    dict2 = {'ip': ip}
    dnew = Merge(dict2, dict1)
    #print(dnew)
    return jsonify(dnew), 200



@app.route("/js", methods=["GET"])
def ipjs():
    ip = request.environ.get('HTTP_X_REAL_IP', request.remote_addr)
    dict1 = test_free(ip)
    dict2 = {'ip': ip}
    dnew = Merge(dict2, dict1)
    # to_str = str(dnew)
    strrr = "var ip_data =" + str(dnew)
    return strrr, 200


def Merge(dict1, dict2):
    res = {**dict1, **dict2}
    return res


if __name__ == '__main__':
    app.run(
        host="192.168.123.33",
        port=int("10746")
    )
